package pkg.hicph.org;

import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainGameMap extends MapActivity implements OnClickListener, Runnable {
	
	// Timers
	TimerTask refreshTask;
	final Handler handler = new Handler();
	Timer t = new Timer();
	Thread threadLoops, threadSleep, threadStories;
	int frequency = 10000;
	int countSecs = 0;
	Boolean refreshing = false;
	
	//EAting places - EAT_MODE
	Place [] activeEatingPlaces = new Place[5];
	
	Boolean limitTriggers = false;
	
	// Preference file
    public static final String PREF_FILE = "pf_file";
    private SharedPreferences preferences;

	// General Activity
    private MapView mapView;
    
    // Score and timer
    int matchScore;
    int matchTime;
    
    // Player State Thread Timer
    TimerTask refreshPlayerStateTask;
	final Handler handlerPlayerState = new Handler();
	Timer tPlayerState = new Timer();
	
	// Location
	private static final int NEWER_CHECK = 1000 * 2;
    private Location bestLocation;
    private LocationManager locationManager;
    private LocationListener locationListener;
    private Double latDoubleValue = (double) 0, lonDoubleValue = (double) 0;
    public Double myLon = (double) 0, myLat = (double) 0;
	
	// Overlays
	private List<Overlay> playerOverlays;
	private List<Overlay> mapOverlaysPlaces;
	private Drawable 
					unknownPlacesMarker,
					playerMarker,
					playerNormalMarker,
					playerSadMarker,
					playerHappyMarker,
					knownPlaceMarker,
					workPlaceMarker,
					funPlaceMarker,
					sleepPlaceMarker,
					eatPlaceMarker;
	
	private OverlayManager 
					playerOverlayManager,
					playerNormalOverlayManager,
					playerSadOverlayManager,
					playerHappyOverlayManager;
	
    // Radar Overlays
//    private OverlayItem placesOverlay;
    private PlaceOverlayManager 
    			unknownPlacesOverlayManager, 
    			knownPlacesOverlayManager,
    			workPlacesOverlayManager, 
    			funPlacesOverlayManager, 
    			sleepPlacesOverlayManager,
    			eatPlacesOverlayManager;
	
	// UI
    private PowerManager.WakeLock wl; 
    public ProgressBar pBar;
    public LinearLayout framePBar;
    public Button centerMapBtn, tipsBtn, actionButton;
//    public TextView phText, mhText, timeText, moneyText;
    public TextView goalText, moneyText, pBarText;
    
    public OverlayItem playerIcon;
    
    // PLACES
    public int totalPlaces = 0;
    public Place closestSleepingPlace = new Place();
	public Place safestSleepingPlace;
	private Place closestBeggingPlace;
	
	//GENERAL
	public Random randomizer = new Random();
	private Place closestSellingPlace;
	
	
    	
	 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(
        WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);  
        wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen"); 
        
        // creates the activity
        setContentView(R.layout.maingamemap);        
        registerViews();
        setupOnClickListeners();
        
        
        // Game logic cleanup
        Utils.player = new Player();
        
        Utils.achievedInSession = 0;
        Utils.activeEvent = new Event();
        Utils.activeMemory = new Memory();
        Utils.activePlace = new Place();
        Utils.begChances = 0;
        Utils.begCount = 0;
        Utils.sellChances = 0;
        Utils.sellCount = 0;
        Utils.visitedBins = "";
        Utils.sleepSafety = 0;
        
        
        
        
        loadPosPrefs();
        
        Log.d("MGM", "latDoubleValue" + latDoubleValue);
        Log.d("MGM", "lonDoubleValue" + lonDoubleValue);
        
        setUpContainers();
       
	    playerOverlays = mapView.getOverlays();
	    mapOverlaysPlaces = mapView.getOverlays();   
	    
	    // Player UI
	    playerNormalMarker = this.getResources().getDrawable(R.drawable.normal_icon_50);
	    playerNormalOverlayManager = new OverlayManager(playerNormalMarker, this);
	    
	    playerSadMarker = this.getResources().getDrawable(R.drawable.sad_icon_50);
	    playerSadOverlayManager = new OverlayManager(playerSadMarker, this);
	    
	    playerHappyMarker = this.getResources().getDrawable(R.drawable.happy_icon_50);
	    playerHappyOverlayManager = new OverlayManager(playerHappyMarker, this);
	    
	    playerOverlayManager = new OverlayManager(playerNormalMarker, this);
	    
	    // PLACES UI
	    workPlaceMarker = this.getResources().getDrawable(R.drawable.work_icon_50);
	    workPlacesOverlayManager = new PlaceOverlayManager(workPlaceMarker, this);
	    
	    funPlaceMarker = this.getResources().getDrawable(R.drawable.fun_icon_50_2);
	    funPlacesOverlayManager = new PlaceOverlayManager(funPlaceMarker, this);
	    
	    sleepPlaceMarker = this.getResources().getDrawable(R.drawable.sleep_icon_50);
	    sleepPlacesOverlayManager = new PlaceOverlayManager(sleepPlaceMarker, this);
	    
	    eatPlaceMarker = this.getResources().getDrawable(R.drawable.eat_icon_50);
	    eatPlacesOverlayManager = new PlaceOverlayManager(eatPlaceMarker, this);
	    
	    
//	    knownPlaceMarker = this.getResources().getDrawable(R.drawable.dotblue);
//	    knownPlacesOverlayManager = new PlaceOverlayManager(knownPlaceMarker, this);
	    
	    unknownPlacesMarker = this.getResources().getDrawable(R.drawable.question_icon_50);
	    unknownPlacesOverlayManager = new PlaceOverlayManager(unknownPlacesMarker, this);

	    
        if(latDoubleValue!=0 && lonDoubleValue!=0) {
            // if we already have a clear position
            // set the center position of the game

            Log.d("CENTER LAT", latDoubleValue+"");
            Log.d("CENTER LON", lonDoubleValue+"");
            
            Utils.player.pos = new GeoPoint(latDoubleValue.intValue(), lonDoubleValue.intValue());
            
            mapView.setSatellite(true);
            mapView.setStreetView(false);
            mapView.setTraffic(false);
            mapView.getController().setZoom(21);
            mapView.setBuiltInZoomControls(false);
            mapView.displayZoomControls(false);
            mapView.setClickable(true);
            mapView.getController().stopPanning();
            mapView.setHapticFeedbackEnabled(true);
            mapView.getController().setCenter(Utils.player.pos);
        
            // Add the point to the mapview
            playerIcon = new OverlayItem(Utils.player.pos, "", "");
            playerOverlayManager.addOverlay(playerIcon);
            
            playerOverlays.add(playerOverlayManager);
            
        } else {
            
            // otherwise set the variable for setting it 
            // at the first clear location we have
        
        }
        
        
               
    }

	private void loadPosPrefs() {
        
        preferences = getSharedPreferences(PREF_FILE, MODE_PRIVATE);

    	lonDoubleValue = (double) preferences.getInt("lonDoubleValuePref", 0);
        latDoubleValue = (double) preferences.getInt("latDoubleValuePref", 0);
        
        myLat = (double) preferences.getInt("latDoubleValue", 0);
        myLon = (double) preferences.getInt("lonDoubleValue", 0);
    }
	
	
	public void reloadMyValues() {
        myLat = (double) preferences.getInt("latDoubleValue", 0);
        myLon = (double) preferences.getInt("lonDoubleValue", 0);
	}

	private void setUpContainers() {

	    mapView 	= (MapView) findViewById(R.id.mapview);
	    
	    pBar		= (ProgressBar) findViewById(R.id.progressbar);
	    framePBar	= (LinearLayout) findViewById(R.id.frame_pg);
	    goalText	= (TextView) findViewById(R.id.goal_text);
	    moneyText 	= (TextView) findViewById(R.id.money_text);
	    pBarText	= (TextView) findViewById(R.id.pg_text);
	    
	    centerMapBtn = (Button) findViewById(R.id.center_map_button);
	    tipsBtn = (Button) findViewById(R.id.tips_button);
	    actionButton = (Button) findViewById(R.id.action_button);
		
	}

	private void locateMe() {

	    // Acquire a reference to the system Location Manager
	    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

//	    Log.d("LOCATEME", " CALLED *************************************************");
	    
	    // Define a listener that responds to location updates
	    locationListener = new LocationListener() {
	        
	        public void onLocationChanged(Location location) {

	            if( isBetterLocation(location, bestLocation) ) {

	                // if the new location is the most accurate
	                // set it as the current best location
	                bestLocation = location;

	                latDoubleValue = location.getLatitude();
	                lonDoubleValue = location.getLongitude();

	                if (latDoubleValue != 0 && lonDoubleValue != 0) {

	                    // Called when a new location is found by the GPS location
	                    // provider update the lat and lon local values
	                    latDoubleValue = location.getLatitude() * 1E6;
	                    lonDoubleValue = location.getLongitude() * 1E6;

	                    Utils.player.pos = new GeoPoint(latDoubleValue.intValue(), lonDoubleValue.intValue());

	                    if(playerOverlays.size() != 0) {
	                        playerOverlayManager.removeOverlay(playerIcon);
	                        playerOverlays.remove(playerOverlayManager);
	                    }

	                    // Add the point to the mapview
	                    playerIcon = new OverlayItem(Utils.player.pos, "", "player");
	                    playerOverlayManager.addOverlay(playerIcon);
	                    
	                    if(Utils.player.mood>=70){
	               		 Log.d("P.SET2", "happy");
	                    	 playerIcon.setMarker(playerHappyMarker);
	                    }
	                    else if(Utils.player.mood>=40){
	                   	 Log.d("P.SET2", "normal");
	                    	 playerIcon.setMarker(playerNormalMarker);
	                    }
	                    else {
	                   	 Log.d("P.SET2", "sad");
	                    	 playerIcon.setMarker(playerSadMarker);
	                    }
	                    
	                    playerOverlays.add(playerOverlayManager);
	                    

	                    mapView.postInvalidate();
	                    
	                    mapView.setSatellite(true);
	                    mapView.setStreetView(false);
	                    mapView.setTraffic(false);
	                    mapView.getController().setZoom(21);
	                    mapView.setBuiltInZoomControls(false);
	                    mapView.displayZoomControls(false);
	                    mapView.setClickable(true);
	                    mapView.getController().stopPanning();
	                    mapView.setHapticFeedbackEnabled(true);
	                    
	                    

	                }

	            }
	            
	            updateDistances();
	            
	            updateUI(true);
			}

            public void onStatusChanged(String provider, int status,
                    Bundle extras) {
            }

            public void onProviderEnabled(String provider) {

            }

            public void onProviderDisabled(String provider) {
            }

//            public void updateServerPosition() {
//
//                Connection.setPosition(gameSessionID, latDoubleValue.intValue(), lonDoubleValue.intValue());
//            }

        };

        // Register the listener with the Location Manager to receive location
        // updates from the GPS and the cell towers
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locationListener);
        //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

    }

	
	@Override
	protected boolean isRouteDisplayed() {
		// do not visualize routing information
		return false;
	}
	
	// because of android weird location system
	// the newer location is not always the best
	// so I included some basic logic to check
	// which one is the most accurate location
	protected boolean isBetterLocation(Location location, Location currentBestLocation) {
	    if (currentBestLocation == null) {
	        // A new location is always better than no location
	        return true;
	    }

	    // Check whether the new location fix is newer or older
	    long timeDelta = location.getTime() - currentBestLocation.getTime();
	    boolean isSignificantlyNewer = timeDelta > NEWER_CHECK;
	    boolean isSignificantlyOlder = timeDelta < -NEWER_CHECK;
	    boolean isNewer = timeDelta > 0;

	    // If it's been more than NEWER_CHECK since the current location, use the new location
	    // because the user has likely moved
	    if (isSignificantlyNewer) {
	        return true;
	    // If the new location is more than NEWER_CHECK older, it must be worse
	    } else if (isSignificantlyOlder) {
	        return false;
	    }

	    // Check whether the new location fix is more or less accurate
	    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
	    boolean isLessAccurate = accuracyDelta > 0;
	    boolean isMoreAccurate = accuracyDelta < 0;
	    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

	    // Check if the old and new location are from the same provider
	    boolean isFromSameProvider = isSameProvider(location.getProvider(),
	            currentBestLocation.getProvider());

	    // Determine location quality using a combination of timeliness and accuracy
	    if (isMoreAccurate) {
	        return true;
	    } else if (isNewer && !isLessAccurate) {
	        return true;
	    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
	        return true;
	    }
	    return false;
	}
	
	public void loadPlacesUI(){
    	
		int totalPlaces = 0;
		
		// setups proper counting according to array
    	switch(Utils.gamePhase){
    	
    	case Utils.START_EAT_MODE:
    		
    		totalPlaces = Utils.eatingPlacesCount;
    		
    		cleanEatPlacesOverlays();
    		
    		for (int j = 0; j < totalPlaces; j++){
    			
    			eatPlacesOverlayManager.removeOverlay(Utils.eatingPlaces[j].icon);
        		
    			if(Utils.player.money >= 30 && Utils.eatingPlaces[j].action.equalsIgnoreCase("eat healthy food")){
    				Utils.eatingPlaces[j].icon = new OverlayItem(Utils.eatingPlaces[j].gpoint, Utils.eatingPlaces[j].name, j+"");
            		eatPlacesOverlayManager.addOverlay(Utils.eatingPlaces[j].icon);
            		Utils.eatingPlaces[j].icon.setMarker(eatPlaceMarker);
    			}
    			else if(Utils.player.money >= 20 && Utils.eatingPlaces[j].action.equalsIgnoreCase("eat junk food")){
    				Utils.eatingPlaces[j].icon = new OverlayItem(Utils.eatingPlaces[j].gpoint, Utils.eatingPlaces[j].name, j+"");
            		eatPlacesOverlayManager.addOverlay(Utils.eatingPlaces[j].icon);
            		Utils.eatingPlaces[j].icon.setMarker(eatPlaceMarker);
    			}
            		
    	    }
    		
    		eatPlacesOverlayManager.populateNow();
        	
        	mapOverlaysPlaces.add(eatPlacesOverlayManager);
        	
        	mapView.postInvalidate();
        	
    		break;
    	
    	case Utils.START_HUNGRY_MODE:
    		
    		totalPlaces = Utils.eatingPlacesCount;
    		
    		for (int j = 0; j < totalPlaces; j++){
        		
            		
        		Utils.eatingPlaces[j].icon = new OverlayItem(Utils.eatingPlaces[j].gpoint, Utils.eatingPlaces[j].name, j+"");
        		eatPlacesOverlayManager.addOverlay(Utils.eatingPlaces[j].icon);
        		Utils.eatingPlaces[j].icon.setMarker(eatPlaceMarker);
        		
    	    }
    		
    		eatPlacesOverlayManager.populateNow();
        	
        	mapOverlaysPlaces.add(eatPlacesOverlayManager);
        	
        	mapView.postInvalidate();
        	
        	
    		
    		break;
    		
    	case Utils.PLAY_RECYCLE_MODE:
    		
    		cleanEatPlacesOverlays();
    		
//    		totalPlaces = Utils.eatingPlacesCount;
//    		
//    		cleanEatPlacesOverlays();
//    		
//    		for (int j = 0; j < totalPlaces; j++){
//    			
//    			eatPlacesOverlayManager.removeOverlay(Utils.eatingPlaces[j].icon);
//        		
//    			if(Utils.player.money >= 30 && Utils.eatingPlaces[j].action.equalsIgnoreCase("eat healthy food")){
//    				Utils.eatingPlaces[j].icon = new OverlayItem(Utils.eatingPlaces[j].gpoint, Utils.eatingPlaces[j].name, j+"");
//            		eatPlacesOverlayManager.addOverlay(Utils.eatingPlaces[j].icon);
//            		Utils.eatingPlaces[j].icon.setMarker(eatPlaceMarker);
//    			}
//    			else if(Utils.player.money >= 20 && Utils.eatingPlaces[j].action.equalsIgnoreCase("eat junk food")){
//    				Utils.eatingPlaces[j].icon = new OverlayItem(Utils.eatingPlaces[j].gpoint, Utils.eatingPlaces[j].name, j+"");
//            		eatPlacesOverlayManager.addOverlay(Utils.eatingPlaces[j].icon);
//            		Utils.eatingPlaces[j].icon.setMarker(eatPlaceMarker);
//    			}
//            		
//    	    }
//    		
//    		eatPlacesOverlayManager.populateNow();
//        	
//        	mapOverlaysPlaces.add(eatPlacesOverlayManager);
//        	
//        	mapView.postInvalidate();
        	
    		break;
    	}

    }
	
	public void updateDistances(){
    	
    	float [] results = new float[3];
    	
    	int totalPlaces = 0;
		
		// setups proper counting according to array
    	switch(Utils.gamePhase){
    	
    	case Utils.PLAY_EAT_MODE:
    		
    		totalPlaces = Utils.eatingPlacesCount;
    		
    		for (int i = 0; i < totalPlaces; i++){
            	
            	Location.distanceBetween(
            			Utils.eatingPlaces[i].latE6/1E6, 
            			Utils.eatingPlaces[i].lonE6/1E6,
    					Utils.player.pos.getLatitudeE6()/1E6, 
    					Utils.player.pos.getLongitudeE6()/1E6, 
    					results);

            	Utils.eatingPlaces[i].dist = results[0];
            	
            	// if poor and it is a healthy place, it skips
            	if(Utils.player.money < 30 && Utils.eatingPlaces[i].action.equalsIgnoreCase("eat healthy food")){
            		
            	}
            	else {
            		if (Utils.eatingPlaces[i].dist < 4 && !limitTriggers){
                		// it is closer than XX meters
                		limitTriggers = true;
                		Utils.activePlace = Utils.eatingPlaces[i];
                		Log.d("DIST","ACTIVATE PLACE");
                		
                		Utils.gamePhase = Utils.PAUSE_EAT_MODE;
                		
                		Intent eatPlaceIntent = new Intent(this, EatPlaceScreen.class);
                		this.startActivity(eatPlaceIntent);
                		
                	}
                	else if(Utils.activePlace.id == Utils.eatingPlaces[i].id){
                		
                		if(Utils.eatingPlaces[i].dist >= 4)limitTriggers = false;	
                	}
            	}
            	
            	
            }
    		
    		break;
    	
    	case Utils.PLAY_HUNGRY_MODE:
    		
    		totalPlaces = Utils.eatingPlacesCount;
    		
    		for (int i = 0; i < totalPlaces; i++){
            	
            	Location.distanceBetween(
            			Utils.eatingPlaces[i].latE6/1E6, 
            			Utils.eatingPlaces[i].lonE6/1E6,
    					Utils.player.pos.getLatitudeE6()/1E6, 
    					Utils.player.pos.getLongitudeE6()/1E6, 
    					results);

            	Utils.eatingPlaces[i].dist = results[0];
            	
            	if (Utils.eatingPlaces[i].dist < 4 && !limitTriggers){
            		// it is closer than XX meters
            		limitTriggers = true;
            		Utils.activePlace = Utils.eatingPlaces[i];
            		Log.d("DIST","ACTIVATE PLACE");
            		
            		Utils.gamePhase = Utils.PAUSE_HUNGRY_MODE;
            		
            		Intent eatPlaceIntent = new Intent(this, EatPlaceScreen.class);
            		this.startActivity(eatPlaceIntent);
            		
            	}
            	else if(Utils.activePlace.id == Utils.eatingPlaces[i].id){
            		
            		if(Utils.eatingPlaces[i].dist >= 4)limitTriggers = false;	
            	}
            }
    		
    		break;
    		
    	case Utils.PLAY_RECYCLE_MODE :
    		
    		totalPlaces = Utils.trashCansPlacesCount;
    		
    		Log.d("RECYCLE","UPDATE UI");
    		
    		for (int i = 0; i < totalPlaces; i++){
            	
            	Location.distanceBetween(
            			Utils.trashCansPlaces[i].latE6/1E6, 
            			Utils.trashCansPlaces[i].lonE6/1E6,
    					Utils.player.pos.getLatitudeE6()/1E6, 
    					Utils.player.pos.getLongitudeE6()/1E6, 
    					results);

            	Utils.trashCansPlaces[i].dist = results[0];
            	
            	if (Utils.trashCansPlaces[i].dist < 4 && !limitTriggers){
            		// it is closer than XX meters
            		
            		if(!Utils.visitedBins.contains((Utils.trashCansPlaces[i].id + ""))){
            			limitTriggers = true;
                		Utils.activePlace = Utils.trashCansPlaces[i];
                		Log.d("RECYCLE","ACTIVATE PLACE");
                		
                		goalText.setTextSize(18);
                		goalText.setText("You are close enough to a trash bin.");
                		
                		actionButton.setText("Click here to recycle");
                		actionButton.setVisibility(0);
            		}
            		else {
            			Utils.showToastLong(this, "You have already been in this bin.");
            		}
            		
            		
            		
            		
            	}
            	else if(Utils.activePlace.id == Utils.trashCansPlaces[i].id){
            		
            		if(Utils.trashCansPlaces[i].dist >= 4) {
            			limitTriggers = false;
            			
            			//Utils.activePlace = null;
            			
            			goalText.setTextSize(18);
                		goalText.setText("Find trash bins and recycle.");
                		
            			actionButton.setVisibility(4);
            			Log.d("RECYCLE","DEACTIVATE PLACE");
            		}
            	}
            }
    		
    		break;
    		
    	case Utils.PLAY_SLEEP_MODE:
    		
    		Log.d("UD.SLEEP", "UPDATING");
    		
    		totalPlaces = Utils.sleepingPlacesCount;
    		
    		Integer maxSafety = 0;
    		Double noSafe = 0.0, radius = 0.0;
    		
    		closestSleepingPlace = Utils.sleepingPlaces[0];
    		
    		for (int i = 0; i < totalPlaces; i++){
            	
            	Location.distanceBetween(
            			Utils.sleepingPlaces[i].latE6/1E6, 
            			Utils.sleepingPlaces[i].lonE6/1E6,
    					Utils.player.pos.getLatitudeE6()/1E6, 
    					Utils.player.pos.getLongitudeE6()/1E6, 
    					results);

            	Utils.sleepingPlaces[i].dist = results[0];
            	
            	Log.d("Place Distance", Utils.sleepingPlaces[i].dist + "");
            	
            	// if it is closer than previous closest place
            	if(Utils.sleepingPlaces[i].dist <= closestSleepingPlace.dist){
            		
            		closestSleepingPlace = Utils.sleepingPlaces[i];
            		
            		Log.d("C.S.Place", closestSleepingPlace.desc + ", " + closestSleepingPlace.dist);
            		
            		maxSafety = Integer.valueOf(closestSleepingPlace.desc);
            		
            		radius = 10.0 + (100.0 - maxSafety);
            		
            		noSafe = (0.1-(radius*0.001)) * (closestSleepingPlace.dist*closestSleepingPlace.dist);
            		
            		Log.d("No SAFE", noSafe + "");
            		
            		Utils.sleepSafety = (int)(maxSafety - noSafe);
                	
                	if(Utils.sleepSafety<0) Utils.sleepSafety = 0;
                	
            	}

            	
            }
    		
    		break;
    		
    	case Utils.PLAY_BEG_MODE:
    		
    		Log.d("UD.BEG", "UPDATING");
    		
    		totalPlaces = Utils.beggingPlacesCount;
    		
    		Integer maxBegChance = 0;
    		
    		closestBeggingPlace = Utils.beggingPlaces[0];
    		
    		for (int i = 0; i < totalPlaces; i++){
            	
            	Location.distanceBetween(
            			Utils.beggingPlaces[i].latE6/1E6, 
            			Utils.beggingPlaces[i].lonE6/1E6,
    					Utils.player.pos.getLatitudeE6()/1E6, 
    					Utils.player.pos.getLongitudeE6()/1E6, 
    					results);

            	Utils.beggingPlaces[i].dist = results[0];
            	
            	Log.d("Place Distance", Utils.beggingPlaces[i].dist + "");
            	
            	// if it is closer than previous closest place
            	if(Utils.beggingPlaces[i].dist <= closestBeggingPlace.dist){
            		
            		closestBeggingPlace = Utils.beggingPlaces[i];
            		
            		Log.d("C.S.Place", closestBeggingPlace.desc + ", " + closestBeggingPlace.dist);
            		
            		maxBegChance = 70;
            		
//            		distLimiter = (0.1-(radius*0.001)) * (closestBeggingPlace.dist*closestBeggingPlace.dist);
            		
            		Utils.begChances = (int)(maxBegChance - closestBeggingPlace.dist/2);
                	
                	if(Utils.begChances<0) Utils.begChances = 0;
                	
            	}

            	
            }
    		
    		break;
    		
    	case Utils.PLAY_HF_MODE:
    		
    		Log.d("UD.HF", "UPDATING");
    		
    		totalPlaces = Utils.husForbiPlacesCount;
    		
    		Integer maxSellChance = 0;
    		
    		closestSellingPlace = Utils.husForbiPlaces[0];
    		
    		for (int i = 0; i < totalPlaces; i++){
            	
            	Location.distanceBetween(
            			Utils.husForbiPlaces[i].latE6/1E6, 
            			Utils.husForbiPlaces[i].lonE6/1E6,
    					Utils.player.pos.getLatitudeE6()/1E6, 
    					Utils.player.pos.getLongitudeE6()/1E6, 
    					results);

            	Utils.husForbiPlaces[i].dist = results[0];
            	
            	Log.d("Place Distance", Utils.husForbiPlaces[i].dist + "");
            	
            	// if it is closer than previous closest place
            	if(Utils.husForbiPlaces[i].dist <= closestSellingPlace.dist){
            		
            		closestSellingPlace = Utils.husForbiPlaces[i];
            		
            		Log.d("C.S.Place", closestSellingPlace.desc + ", " + closestSellingPlace.dist);
            		
            		maxSellChance = 90;
            		
//            		distLimiter = (0.1-(radius*0.001)) * (closestBeggingPlace.dist*closestBeggingPlace.dist);
            		
            		Utils.sellChances = (int)(maxSellChance - closestSellingPlace.dist*2);
                	
                	if(Utils.sellChances<0) Utils.sellChances = 0;
                	
            	}

            	
            }
    		
    		break;
    	}
    	
    	Log.d("U.DIST", "");
    	
        
        
        
    }
	
	public void onResume() {
        
        wl.acquire();
        
        refreshing = true;

        switch(Utils.gamePhase) {

        case Utils.NEWLY_CREATED:
        	
        	threadLoops = new Thread(this);
            threadLoops.start();
            
        	Log.d("LOC. GAME PHASE", "Game created");
        	
        	Utils.gamePhase = Utils.START_HUNGRY_MODE;
        	
        	Utils.canShowStories = true;
        	
        	Utils.player.dayStory = "The day started with you feeling very hungry, but completely out of money.";
        	
        	loadPlacesUI();
        	
        	goalText.setText("Find a place to get food.");
        	moneyText.setText("You have " + (int)Utils.player.money +" dkk.");

            updateUI(true);
            
            Utils.gamePhase = Utils.PLAY_HUNGRY_MODE;
            limitTriggers = false;

            break;
            
        case Utils.START_MONEY_PROBLEM:
        	
        	Intent chooseWorkIntent = new Intent(this, ChooseMoneyScreen.class);
    		this.startActivity(chooseWorkIntent);
        	
    		break;
    		
        case Utils.START_SLEEP_MODE:
        	
        	threadLoops = new Thread(this);
            threadLoops.start();
            
            Utils.canShowStories = true;
        	
        	cleanEatPlacesOverlays();
        	
        	loadPlacesUI();
        	
        	goalText.setText("Find a good place to sleep.");
        	moneyText.setText("This place is " + Utils.sleepSafety +"% safe.");

        	Utils.gamePhase = Utils.PLAY_SLEEP_MODE;
        	
        	actionButton.setVisibility(0);
        	actionButton.setText("Click to sleep here");
            
        	updateUI(true);
            
            

            break;
        
        
        case Utils.END_SLEEP_MODE:

        	threadLoops = new Thread(this);
            threadLoops.start();
        	
        	actionButton.setVisibility(8);
        	
        	goalText.setText("ZZZzzzZZZzzz...");
        	moneyText.setText("RONC!");
        	
        	Utils.isTimer = true;
        	Utils.canShowStories = false;
        	
			framePBar.setVisibility(0);
			pBarText.setText("You are sleeping...");
			
			pBar.setMax(20+(int)(Math.random()*8));
			
			countSecs = 0;
			
			pBar.setProgress(countSecs);
			

        	break;
            
        case Utils.END_OF_DAY:

			Intent newGameIntent = new Intent(this, EndOfDayDialog.class);

        	break;
        	
        case Utils.START_RECYCLE_MODE:
        	
        	threadLoops = new Thread(this);
            threadLoops.start();
        	
        	Utils.canShowStories = true;
        	
        	cleanEatPlacesOverlays();
        	
        	Utils.gamePhase = Utils.PLAY_RECYCLE_MODE;
        	
        	limitTriggers = false;
        	
        	goalText.setTextSize(18);
        	goalText.setText("Find trash bins and recycle.");
        	
        	Utils.showToastLong(this, "Tip: Go near a trash bin and click the button. You'll get money for the bottles and cans you find.");

        	updateUI(false);

        	break;
        	
        //===== CURRENT WORK ======================================================//	
        case Utils.START_HF_MODE:
        	
        	threadLoops = new Thread(this);
            threadLoops.start();
        	
        	Utils.canShowStories = true;

        	cleanEatPlacesOverlays();
        	
        	goalText.setText("Go to busy areas to sell Hus Forbi.");
        	Utils.showToastLong(this, "Tip: Go to busy areas and click the button to sell. Wait a bit and get 8 dkk for each copy sold.");
        	
        	Utils.gamePhase = Utils.PLAY_HF_MODE;
        	
        	actionButton.setVisibility(0);
        	actionButton.setText("Click to sell Hus Forbi");
        	
        	updateUI(false);
        	
        	break;
        
        case Utils.START_BEG_MODE:
        	
        	threadLoops = new Thread(this);
            threadLoops.start();
        	
        	Utils.canShowStories = true;
        	
        	cleanEatPlacesOverlays();
        	
        	goalText.setText("Go to busy areas and beg.");
        	
        	Utils.showToastLong(this, "Tip: Go to busy areas and click the button. Wait and receive money from people.");
        	
        	Utils.gamePhase = Utils.PLAY_BEG_MODE;
        	
        	actionButton.setVisibility(0);
        	actionButton.setText("Click to beg");
        	
        	updateUI(false);
        	
        	break;
        	
        case Utils.NORMAL:

        	updateUI(false);

        	break;
        	
        case Utils.START_EAT_MODE:
        	
        	threadLoops = new Thread(this);
            threadLoops.start();
        	
        	Utils.canShowStories = true;

        	actionButton.setVisibility(8);
        	
        	loadPlacesUI();
        	
        	if(Utils.player.money >= 30){
        		goalText.setText("You can go eat at any food place in the map.");
        	}
        	else {
        		goalText.setText("Go to a snack food place to eat.");
        	}

        	moneyText.setText("You have " + (int)Utils.player.money +" dkk.");

            updateUI(true);
            
            Utils.gamePhase = Utils.PLAY_EAT_MODE;
            limitTriggers = false;

            break;
            
            
        case Utils.PLAY_HUNGRY_MODE :
        	
        	threadLoops = new Thread(this);
            threadLoops.start();
        	
        	Utils.canShowStories = true;
        	
        	break;
        	
        case Utils.PLAY_SLEEP_MODE :
        	
        	threadLoops = new Thread(this);
            threadLoops.start();
        	
        	Utils.canShowStories = true;
        	
        	break;
        	
        case Utils.PLAY_HF_MODE :
        	
        	threadLoops = new Thread(this);
            threadLoops.start();
        	
        	Utils.canShowStories = true;

        	break;
        	
        case Utils.PLAY_BEG_MODE :
        	
        	threadLoops = new Thread(this);
            threadLoops.start();
        	
        	Utils.canShowStories = true;

        	break;
        	
        }
        
        
        
        locateMe();

        
        
//      Log.d("SP XML", "CALLED");
        
        super.onResume();
		
	}

	// Checks whether two providers are the same 
	private boolean isSameProvider(String provider1, String provider2) {
	    if (provider1 == null) {
	      return provider2 == null;
	    }
	    return provider1.equals(provider2);
	}

	public void onPause() {
		// Remove the listener you previously added
		locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		locationManager.removeUpdates(locationListener);
		
		stopRefreshing();
		
//		if(refreshing) {
//		    // not in the first time
//		   
//		    wl.release(); 
//		}
			
					
		super.onPause();
	}
	
	public void stopRefreshing(){
		
		refreshing = false;
	}

	@Override
	public void onClick(View v) {

		switch(v.getId()) {
    	
    	case R.id.center_map_button:
    		
    		mapView.getController().setCenter(Utils.player.pos);
    		
    		break;
    	
		
		case R.id.tips_button:
		
			switch(Utils.gamePhase){
			
			case Utils.PLAY_RECYCLE_MODE :
				
				Utils.showToastLong(this, "Tip: Go near a trash can and click the button. You'll get money for the bottles and cans you find.");
			
				break;
				
			default :
				
//				Random aux = new Random();
//				
//				Utils.activeEvent = Utils.globalEvents[aux.nextInt(Utils.totalEvents)];
//				
//				Intent eventIntent = new Intent(this, EventScreen.class);
//	    		this.startActivity(eventIntent);
				
				break;
			}
		
			break;

		
		case R.id.action_button:
			
			switch(Utils.gamePhase){
			
			case Utils.PLAY_RECYCLE_MODE :
				
				Log.d("recycle","clicked");
				
				// gets some money
				int foundMoney = (int)(Math.random()*15);
				
				if(foundMoney == 0){
					Utils.showToastLong(this, "You found nothing in this bin.");
				}else {
					Utils.showToastLong(this, "You found "+ foundMoney +" worth of bottle and cans in this bin!");
				}
				
				Utils.player.money += foundMoney;
				
				Utils.visitedBins = Utils.visitedBins + "_" + Utils.activePlace.id;
				
				actionButton.setVisibility(4);
				
				loadPlacesUI();
				
				if(Utils.player.money >= 30){
					goalText.setTextSize(18);
					goalText.setText("Now you have enough money for a full meal!");
					
					Intent stopWorkIntent = new Intent(this, StopWorkScreen.class);
		    		this.startActivity(stopWorkIntent);
				}
				else if(Utils.player.money >= 20){
					goalText.setTextSize(18);
					goalText.setText("You have enough for a snack, but you can keep going to have enough for a full meal!");
					
					
					Intent stopWorkIntent = new Intent(this, StopWorkScreen.class);
		    		this.startActivity(stopWorkIntent);
				}
				else {
					goalText.setTextSize(18);
					goalText.setText("Find another trash bin.");
				}

				updateUI(false);
			
				break;
				
			case Utils.PLAY_SLEEP_MODE :
				
				Utils.isTimer = true;
				
				Utils.canShowStories = false;
				
				Log.d("sleep","clicked");
				
				if(Utils.sleepSafety >= 15){
					Intent confirmSleepkIntent = new Intent(this, SleepScreen.class);
		    		this.startActivity(confirmSleepkIntent);
				}
				else {
					Utils.showToastLong(this, "It is impossible to sleep here!");
					Utils.isTimer = false;
					Utils.canShowStories = true;
				}

				updateUI(false);
			
				break;
			
			case Utils.PLAY_BEG_MODE:
				
				Utils.isTimer = true;
				
				Utils.canShowStories = false;
				
				Log.d("BEG", "clicked");
				
				framePBar.setVisibility(0);
				pBarText.setText("You are begging...");
				
				Utils.isBegging = true;
				
				Log.d("begging isBegging", Utils.isBegging + "");
				Log.d("begging and refreshing", refreshing + "");
				
				pBar.setMax(10 + randomizer.nextInt(10));
				
				countSecs = 0;
				
				pBar.setProgress(countSecs);
				
				actionButton.setVisibility(8);
	        	
	        	break;
			
			case Utils.PLAY_HF_MODE:
				
				Utils.isTimer = true;
				
				Utils.canShowStories = false;
				
				Log.d("HF", "clicked");
				
				framePBar.setVisibility(0);
				pBarText.setText("Selling Hus Forbi...");
				
				Utils.isSelling = true;
				
				Log.d("isSelling", Utils.isSelling + "");
				Log.d("selling refresh", refreshing + "");
				
				// improve this based on distance
				pBar.setMax(10 + randomizer.nextInt(10));
				
				countSecs = 0;
				
				pBar.setProgress(countSecs);
				
				actionButton.setVisibility(8);
	        	
	        	break;
			}
			
			break;
			
		
		}

    }
	
	
    private void setupOnClickListeners() {
    	
    	centerMapBtn.setOnClickListener(this);
    	tipsBtn.setOnClickListener(this);
    	actionButton.setOnClickListener(this);

	}
    
    
    
    private void updateUI(Boolean icons){
    	
    	 if(Utils.player.mentalHealth < Utils.minMH || Utils.player.physicalHealth < Utils.minPH 
    			 || Utils.player.mood < Utils.minMO){
    		
    		Utils.player.overallStory += "\n\nDay " + Utils.currentDay + " was your last one: " + Utils.player.dayStory + 
    			" Then, you lost."; 
    		 
    		 
    		Intent endGameIntent = new Intent(this, EndGameScreen.class);
     		this.startActivity(endGameIntent);
    	 }
    	 
    	 moneyText.setText("You have " + (int)Utils.player.money +" dkk.");
    	 
    	 if(Utils.gamePhase == Utils.PLAY_BEG_MODE){
    		 moneyText.setText("Your chance of success here is " + (int)Utils.begChances +"%.");
    		 goalText.setText("Keep begging. You have "+ (int)Utils.player.money + " dkk.");
    	 }
    	 
    	 if(Utils.gamePhase == Utils.PLAY_HF_MODE){
    		 moneyText.setText("You have a " + (int)Utils.sellChances +"% chance of selling one here.");
    		 goalText.setText("Sell newspapers. You have "+ (int)Utils.player.money + " dkk.");
    	 }

    	 if(Utils.gamePhase == Utils.PLAY_SLEEP_MODE){
    		 moneyText.setText("This place is " + Utils.sleepSafety +"% safe.");
    	 }
    	
    	 if(Utils.player.mood>=70){
//    		 Log.d("P.UI", "happy");
         	 playerIcon.setMarker(playerHappyMarker);
         }
         else if(Utils.player.mood>=40){
//        	 Log.d("P.UI", "normal");
         	 playerIcon.setMarker(playerNormalMarker);
         }
         else {
//        	 Log.d("P.UI", "sad");
         	 playerIcon.setMarker(playerSadMarker);
         }
    	 
         mapView.postInvalidate();
         
              
    }

	private void registerViews() {
		centerMapBtn = (Button) this.findViewById(R.id.center_map_button);
		tipsBtn		 = (Button) this.findViewById(R.id.tips_button);
		actionButton = (Button) this.findViewById(R.id.action_button);
		//		btnPower2 = (ImageButton) this.findViewById(R.id.power_button_right);
	}    
    
    private void cleanEatPlacesOverlays() {
	    		
		// cleans the ui overlays
        mapOverlaysPlaces.remove(eatPlacesOverlayManager);
		mapView.postInvalidate();
    	
    }

	@Override
	public void run() {

		while(refreshing){
			
			Log.d("RUNNING","------------------------------------");
			
			if(Utils.canShowStories){
				// Show stories loop
				
				Log.d("LOOP STORIES","--------");
				
				int randIndex = randomizer.nextInt(Utils.totalEvents - 1);
				
				if(randomizer.nextInt(50) < Utils.globalEvents[randIndex].freq && !Utils.globalEvents[randIndex].achieved && !Utils.globalEvents[randIndex].type.equalsIgnoreCase("achieve")){
					
					Log.d("Stories","new story");
					
					Utils.activeEvent = Utils.globalEvents[randIndex];
					Utils.activeEvent.achieved = true;
					
					Utils.achievedInSession++;
					
					Intent eventIntent = new Intent(this, EventScreen.class);
		    		this.startActivity(eventIntent);
					
				}
				else {
					Log.d("Stories","NO story");
				}
			}
			
			if(Utils.isTimer){
				
				// timer loops
				Log.d("LOOP TIMER","========");
				
				switch(Utils.gamePhase){
				
				case Utils.END_SLEEP_MODE :
					
					countSecs++;
					
					if(countSecs > pBar.getMax()){
						Log.d("SLEEPING","FINISHED - END OF GAME");
						
						// stops this timer
						Utils.isTimer = false;
						
						// insert end of day here
						Utils.player.dayStory += " Your day ended after you had some sleep in the streets.";
						
						Utils.gamePhase = Utils.END_GAME_SCREEN;
						
						Intent endGameIntent = new Intent(this, EventScreen.class);
			     		this.startActivity(endGameIntent);
			     		
			     		this.finish();
					
					}
					else {
						pBar.setProgress(countSecs);
					}
					
					
					
					break;
					
				case Utils.PLAY_BEG_MODE :
					
					Log.d("BEG", "refreshing");
					
					// if clicked
					if(Utils.isBegging){
						
						Log.d("BEG", "entered action");
						
						countSecs++;
						
						if(countSecs > pBar.getMax()){
							
							Log.d("BEG","FINISHED");
							
							Utils.isBegging = false;
							Utils.isTimer = false;
							
		
							int aux = (int) (randomizer.nextInt(30) * Utils.begChances * 0.01);
							
							Utils.oldMoney = aux;
							
							Utils.player.money += aux;

							pBar.getHandler().postAtFrontOfQueue(new Runnable (){

								@Override
								public void run() {
									// TODO Auto-generated method stub
									framePBar.setVisibility(8);
									actionButton.setVisibility(0);
									
									Utils.canShowStories = true;
									
									updateUI(false);
									
									if(Utils.oldMoney > 0){
										Utils.begCount++;
										Utils.showToastLong(getBaseContext(), "Somebody gave you "+(int)Utils.oldMoney+" dkk.");
									}	
									else
										Utils.showToastLong(getBaseContext(), "You got nothing.");
									
									Utils.oldMoney = 0;
									
									if(Utils.player.money >= 20){
										
										Utils.canShowStories = false;
										
										Intent stopWorkIntent = new Intent(getBaseContext(), StopWorkScreen.class);
										stopWorkIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
										getBaseContext().startActivity(stopWorkIntent);
										
									}
									
								}
								
							});
							
//							if(aux > 0)
//								Utils.showToastLong(this, "Somebody gave you "+aux+" dkk.");
//							else
//								Utils.showToastLong(this, "You got nothing.");
						
						}
						else {
							pBar.setProgress(countSecs);
						}
						
					}

					break;
					
				case Utils.PLAY_HF_MODE :
					
					Log.d("HF", "refreshing");
					
					// if clicked
					if(Utils.isSelling){
						
						Log.d("HF", "entered action");
						
						countSecs++;
						
						if(countSecs > pBar.getMax()){
							
							Log.d("HF","FINISHED");
							
							Utils.isSelling = false;
							Utils.isTimer = false;
							
							int aux = (int) (randomizer.nextInt(100));
							
							Utils.oldMoney = aux;
							
							if(aux <= Utils.sellChances){
								Utils.player.money += 8;

							}else{
								Utils.oldMoney = 0;
							}
							
							

							pBar.getHandler().postAtFrontOfQueue(new Runnable (){

								@Override
								public void run() {
									// TODO Auto-generated method stub
									framePBar.setVisibility(8);
									actionButton.setVisibility(0);
									
									updateUI(false);
									
									if(Utils.oldMoney > 0){
										Utils.sellCount++;
										Utils.showToastLong(getBaseContext(), "You sold a Hus Forbi copy for 8 dkk.");
									}	
									else
										Utils.showToastLong(getBaseContext(), "You didn't find a buyer.");
									
									Utils.oldMoney = 0;
									
									if(Utils.player.money >= 20){
										
										Intent stopWorkIntent = new Intent(getBaseContext(), StopWorkScreen.class);
										stopWorkIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
										getBaseContext().startActivity(stopWorkIntent);
										
									}
									
								}
								
							});
						
						}
						else {
							pBar.setProgress(countSecs);
						}
						
					}

					break;
				
				}
				
				
				
			}
			
			
			//Log.d("REFRESH","------------------------------------");
			
			
			
//			updateDistances();
			//mapView.postInvalidate();
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
		}
		
	}

	
}
